import tkinter as tk
from tkinter import messagebox


class TimerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("倒计时提醒程序")
        self.root.protocol("WM_DELETE_WINDOW", self.on_exit)  # 禁止直接关闭窗口

        # 设置主窗口居中并置顶
        self.center_window()
        self.root.attributes("-topmost", True)  # 启动时置顶
        self.root.after(100, lambda: self.root.attributes("-topmost", False))  # 100ms后取消置顶

        # 创建时间选择控件
        self.label = tk.Label(root, text="设置倒计时时间：")
        self.label.grid(row=0, column=0, columnspan=6, pady=10, padx=20, sticky="ew")

        # 添加“时”、“分”、“秒”标签
        self.hour_label = tk.Label(root, text="时", font=("Arial", 12))
        self.hour_label.grid(row=1, column=0, padx=5, pady=5)
        self.hour = tk.Spinbox(root, from_=0, to=23, width=5)
        self.hour.grid(row=1, column=1, padx=5, pady=5)

        self.minute_label = tk.Label(root, text="分", font=("Arial", 12))
        self.minute_label.grid(row=1, column=2, padx=5, pady=5)
        self.minute = tk.Spinbox(root, from_=0, to=59, width=5)
        self.minute.grid(row=1, column=3, padx=5, pady=5)

        self.second_label = tk.Label(root, text="秒", font=("Arial", 12))
        self.second_label.grid(row=1, column=4, padx=5, pady=5)
        self.second = tk.Spinbox(root, from_=0, to=59, width=5)
        self.second.grid(row=1, column=5, padx=5, pady=5)

        # 设置默认时间为1分40秒
        self.hour.delete(0, tk.END)
        self.hour.insert(0, "0")  # 小时默认为0
        self.minute.delete(0, tk.END)
        self.minute.insert(0, "1")  # 分钟默认为1
        self.second.delete(0, tk.END)
        self.second.insert(0, "40")  # 秒默认为40

        # 创建按钮
        self.start_button = tk.Button(root, text="开始倒计时", command=self.start_timer)
        self.start_button.grid(row=2, column=0, columnspan=3, padx=20, pady=10, sticky="ew")

        self.stop_button = tk.Button(root, text="停止计时", command=self.stop_timer)
        self.stop_button.grid(row=2, column=0, columnspan=3, padx=20, pady=10, sticky="ew")
        self.stop_button.grid_remove()  # 初始隐藏停止按钮

        self.exit_button = tk.Button(root, text="退出", command=self.on_exit)
        self.exit_button.grid(row=2, column=3, columnspan=3, padx=20, pady=10, sticky="ew")

        # 倒计时显示
        self.timer_label = tk.Label(root, text="00:00:00", font=("Arial", 20))
        self.timer_label.grid(row=3, column=0, columnspan=6, pady=20, padx=20, sticky="ew")

        # 初始化倒计时变量
        self.running = False
        self.total_seconds = 0
        self.after_id = None
        self.initial_seconds = 0  # 保存用户最初设置的时间

        # 调整窗口大小以适应内容
        self.root.update_idletasks()
        self.root.geometry(f"{self.root.winfo_reqwidth()}x{self.root.winfo_reqheight()}")

    def center_window(self, window=None):
        # 设置窗口居中
        if window is None:
            window = self.root
        window.update_idletasks()
        screen_width = window.winfo_screenwidth()
        screen_height = window.winfo_screenheight()
        width = window.winfo_reqwidth()
        height = window.winfo_reqheight()
        x = (screen_width - width) // 2
        y = (screen_height - height) // 2
        window.geometry(f"{width}x{height}+{x}+{y}")

    def start_timer(self):
        if not self.running:
            # 获取用户设置的时间
            hours = int(self.hour.get())
            minutes = int(self.minute.get())
            seconds = int(self.second.get())
            self.total_seconds = hours * 3600 + minutes * 60 + seconds
            self.initial_seconds = self.total_seconds  # 保存用户最初设置的时间

            if self.total_seconds > 0:
                self.running = True
                self.start_button.grid_remove()  # 隐藏开始按钮
                self.stop_button.grid(row=2, column=0, columnspan=3, padx=20, pady=10, sticky="ew")  # 显示停止按钮
                self.update_timer()
            else:
                messagebox.showwarning("警告", "请输入有效的时间！")

    def stop_timer(self):
        self.running = False
        if self.after_id:
            self.root.after_cancel(self.after_id)
            self.after_id = None
        self.stop_button.grid_remove()  # 隐藏停止按钮
        self.start_button.grid(row=2, column=0, columnspan=3, padx=20, pady=10, sticky="ew")  # 显示开始按钮

    def update_timer(self):
        if self.running and self.total_seconds > 0:
            # 更新倒计时显示
            hours, remainder = divmod(self.total_seconds, 3600)
            minutes, seconds = divmod(remainder, 60)
            self.timer_label.config(text=f"{hours:02}:{minutes:02}:{seconds:02}")
            self.total_seconds -= 1

            # 1秒后再次更新
            self.after_id = self.root.after(1000, self.update_timer)
        elif self.running and self.total_seconds == 0:
            # 倒计时结束，弹出提示
            self.running = False
            self.stop_button.grid_remove()  # 隐藏停止按钮
            self.start_button.grid(row=2, column=0, columnspan=3, padx=20, pady=10, sticky="ew")  # 显示开始按钮
            self.show_alert()

    def show_alert(self):
        # 创建一个自定义弹窗
        alert_window = tk.Toplevel(self.root)
        alert_window.title("提醒")
        alert_window.attributes("-topmost", True)  # 始终置顶
        alert_window.grab_set()  # 阻止用户与主窗口交互

        # 设置弹窗大小和居中
        self.center_window(alert_window)

        # 设置弹窗背景颜色和字体
        alert_window.configure(bg="#FF6347")  # 红色背景
        message_label = tk.Label(
            alert_window,
            text="时间到啦！",
            font=("Arial", 24, "bold"),
            bg="#FF6347",
            fg="white"
        )
        message_label.pack(pady=50)

        # 设置按钮
        ok_button = tk.Button(
            alert_window,
            text="确认",
            command=lambda: self.close_alert(alert_window),
            font=("Arial", 16),
            bg="white",
            fg="#FF6347",
            padx=20,
            pady=10
        )
        ok_button.pack(pady=10)

        # 绑定空格键和回车键
        alert_window.bind("<Return>", lambda event: self.close_alert(alert_window))
        alert_window.bind("<space>", lambda event: self.close_alert(alert_window))

        # 设置焦点
        alert_window.focus_force()

    def close_alert(self, alert_window):
        alert_window.destroy()
        # 确认后重新开始倒计时
        if self.initial_seconds > 0:
            self.total_seconds = self.initial_seconds  # 重置为用户最初设置的时间
            self.running = True
            self.start_button.grid_remove()  # 隐藏开始按钮
            self.stop_button.grid(row=2, column=0, columnspan=3, padx=20, pady=10, sticky="ew")  # 显示停止按钮
            self.update_timer()

    def on_exit(self):
        if messagebox.askyesno("退出", "确定要退出程序吗？"):
            self.root.destroy()


if __name__ == "__main__":
    root = tk.Tk()
    app = TimerApp(root)
    root.mainloop()

    # # pyinstaller --onefile --windowed screen_alarm_clock.py